"""Celery应用配置模块
提供Celery应用实例和任务队列配置
"""
import os
from celery import Celery
from config.config import get_config

# 获取配置
config = get_config()

# 创建Celery应用
celery_app = Celery(
    'xbyjob',
    broker=config.REDIS_URL,
    backend=config.REDIS_URL,
    include=[
        'services.executor.tasks',  # 执行器任务
        'services.scheduler.tasks',  # 调度器任务
    ]
)

# 导入Beat调度配置
from services.shared.beat_schedule import beat_schedule, task_routes, task_default_queue

# 确保Beat配置目录存在
os.makedirs(os.path.join(os.path.dirname(__file__), 'beat'), exist_ok=True)

# 配置Celery
celery_app.conf.update(
    task_serializer='json',
    accept_content=['json'],
    result_serializer='json',
    timezone=config.TIMEZONE,
    enable_utc=True,
    task_track_started=True,
    task_time_limit=config.TASK_TIMEOUT,  # 任务超时时间
    worker_max_tasks_per_child=100,  # 每个worker处理的最大任务数
    worker_prefetch_multiplier=1,  # 预取任务数
    task_acks_late=True,  # 任务执行完成后再确认
    task_reject_on_worker_lost=True,  # worker丢失时拒绝任务
    broker_connection_retry_on_startup=True,  # 启动时重试连接
    # 添加Beat调度配置
    beat_schedule=beat_schedule,
)

# 定义默认队列
celery_app.conf.task_default_queue = task_default_queue

# 定义任务路由
celery_app.conf.task_routes = task_routes


def get_celery_app():
    """获取Celery应用实例"""
    return celery_app